package com.nami.logic.service.impl;

import com.nami.basic.bo.client.ClientRespBO;
import com.nami.basic.enums.DownMsgErrorCode;
import com.nami.basic.packet.Packet;
import com.nami.logic.property.PacketProperty;
import com.nami.logic.serializer.Serializer;
import com.nami.logic.service.PacketFactory;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.json.utils.JsonUtils;
import org.springframework.stereotype.Service;

/**
 * 描述：
 *
 * @Author: lbc
 * @Date: 2023-09-25 8:50
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
@Service
@AllArgsConstructor
public class PacketFactoryImpl implements PacketFactory {

    private final PacketProperty packetProperty;


    private Packet createAndSetDefaultValue(Integer cmd) {
        Packet packet = new Packet();
        packet.setMagic((byte) 8);
        packet.setVersion((byte) packetProperty.getVersion());
        packet.setSerial((byte) packetProperty.getSerial());
        packet.setEncrypt((byte) packetProperty.getEncrypt());
        packet.setCmd(cmd);
        return packet;
    }

    @Override
    public Packet newPacket(Integer cmd, Object data) {
        Packet packet = createAndSetDefaultValue(cmd);
        packet.setBody(Serializer.prototype(packet.getSerial()).serialize(data));
        return packet;
    }

    /**
     * @return
     */
    @Override
    public Packet newPacket() {
        Packet packet = new Packet();
        packet.setMagic((byte) 8);
        packet.setVersion((byte) packetProperty.getVersion());
        packet.setSerial((byte) packetProperty.getSerial());
        packet.setEncrypt((byte) packetProperty.getEncrypt());
        return packet;
    }

    @Override
    public Packet newDownmsgRespPacket(Integer cmd, String code, String msg, Object body) {
        ClientRespBO respBO = new ClientRespBO();
        respBO.setCode(code);
        respBO.setMsg(msg);
        respBO.setData(JsonUtils.toJsonString(body));
        return this.newPacket(cmd, respBO);
    }

    @Override
    public Packet newDownmsgErrorRespPacket(Integer cmd, DownMsgErrorCode errorCode, Object body) {
        return this.newDownmsgRespPacket(cmd, errorCode.getCode(), errorCode.getMsg(), body);
    }

    @Override
    public Packet newDownmsgSuccPacket(Integer cmd, Object body) {
        ClientRespBO respBO = new ClientRespBO();
        respBO.setCode(DownMsgErrorCode.SUCCESS.getCode());
        respBO.setMsg(DownMsgErrorCode.SUCCESS.getMsg());
        respBO.setData(JsonUtils.toJsonString(body));
        return this.newPacket(cmd, respBO);
    }


}
